import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JOptionPane;

public class LevelFileWriter {

	protected FileWriter writer;

	protected String mFileName;

	protected boolean mConsoleIsActive;

	public LevelFileWriter(String anXmlFilename) {
		this(anXmlFilename, true);
	}

	public LevelFileWriter(String aFilename, boolean aConsoleActivity) {
		try {
			this.writer = new FileWriter(new File(aFilename + ".lvl"));
			this.mConsoleIsActive = aConsoleActivity;
			this.mFileName = aFilename;

			if (this.mConsoleIsActive) {
				System.out.println("Ouverture du fichier '" + aFilename
						+ ".java" + "'");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null,
					"Erreur lors de l'ouverture du fichier '" + this.mFileName
							+ "'");
			throw new RuntimeException();
		}
	}

	public void print(String aString) {

		// Ecriture dans la console
		if (this.mConsoleIsActive) {
			System.out.print(aString);
		}

		// Ecriture dans un fichier
		try {
			this.writer.append(aString);
		} catch (IOException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null,

			"Erreur lors de l'écriture dans le fichier '" + this.mFileName
					+ "'");
			throw new RuntimeException();
		}
	}

	public void printNewLine() {
		this.print(System.getProperty("line.separator"));
	}

	public void println(String aString) {
		this.print(aString);
		this.printNewLine();
	}

	public void closeStream() {
		if (this.mConsoleIsActive) {
			System.out.println("\nFermeture du fichier '" + this.mFileName
					+ "'");
		}

		try {
			this.writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null,
					"Erreur lors de la fermeture du fichier '" + this.mFileName
							+ "'");
			throw new RuntimeException();
		}
	}

}
